import { DataEnum } from "shared/enums/DataEnum";
import PlayerCharacterEntity, { PlayerCharacterColums } from "shared/modules/data/entity/PlayerCharacterEntity";
import PlayerDataEntity, { PlayerDataColums, PlayerCharacterId } from "shared/modules/data/entity/PlayerDataEntity";
import { DataServiceImpl } from "shared/modules/data/service/DataServiceImpl";

export default class DataServerServiceImpl extends DataServiceImpl {
    /**
    * 获取用户数据存储
    * @returns
    */
    private getPlayerDataStore() {
        return game.GetService('DataStoreService').GetDataStore(DataEnum.PlayerDataStore);
    }
    /**
         * 用户数据缓存
         */
    private playerDataCache = new Map<string, PlayerDataEntity>();
    /**
     * 提交用户数据
     * @param playerId
     * @returns
     */
    submitPlayerData(playerId: number) {


        let success = false;
        let tryTime = 0;
        while (!success && tryTime < 3) {
            tryTime++
            const playerDataStore = this.getPlayerDataStore();
            const playerData = this.getPlayerData(playerId);
            const [setSuccess, errorMessage] = pcall(() => {
                playerDataStore.SetAsync(playerId + "", playerData)
            })
            success = setSuccess
            if (!success) {
                task.wait(1)
            } else {

            }
        }
        if (!success)
            return false
        else return true
    }

    initPlayerData(playerId: number) {
        const data = this.getPlayerData(playerId);
        return data
    }
    /**
     * 获取用户数据
     * @param playerId
     * @returns
     */
    getPlayerData(playerId: number): Ctn.data.IPlayerDataEntity | undefined {
        const playerStorId = playerId + ""
        if (!playerId) {

            return undefined
        }
        let playerData;
        if (this.playerDataCache.has(playerStorId)) {
            playerData = this.playerDataCache.get(playerStorId);
        }
        if (!playerData) {

            const playerDataStore = this.getPlayerDataStore();// 默认用户数据
            playerData = playerDataStore.GetAsync(playerStorId) as unknown as PlayerDataEntity;

            const defaultPlayerData = new PlayerDataEntity();// 默认角色数据
            if (!playerData) {
                playerData = defaultPlayerData;

            } else {
                /** 初始化用户数据 */
                for (const [, i] of pairs(PlayerDataColums)) {
                    // print('i', i)
                    // const column = (i as PlayerDataColums)
                    if (!(playerData[i as PlayerDataColums])) {

                        (playerData[i as PlayerDataColums] as any) = defaultPlayerData[i as PlayerDataColums]
                    }
                }
                // for (const [, i] of pairs(PlayerPack)) {
                //     // print('i', i)
                //     // const column = (i as PlayerDataColums)
                //     if (!(playerData[i as PlayerPack])) {
                //         playerData[i as PlayerPack] = defaultPlayerData[i as PlayerPack]
                //     }
                // }
                /**
                 * 初始化用户角色数据
                 */
                for (const [, i] of pairs(PlayerCharacterId)) {
                    // const column = (i as PlayerDataColums)

                    if (!(playerData[i as PlayerCharacterId])) {// 不存在角色数据时，初始化默认数据
                        const defaultCharacterData = defaultPlayerData[i as PlayerCharacterId];
                        if (defaultCharacterData) {
                            (playerData[i as PlayerCharacterId] as PlayerCharacterEntity) = defaultCharacterData
                            // const defaultCharacter = characters.find(c => c.id === i);
                            // (playerData[i as PlayerCharacterId] as PlayerCharacterEntity)[PlayerCharacterColums.outfits] = defaultCharacter?.outfits + '' || '0'
                        }

                    } else {// 存在角色数据时，进行初始化
                        const playerCharacter = playerData[i as PlayerCharacterId];
                        if (!playerCharacter) continue
                        /**
                         * 用于初始化的模板数据
                         */
                        const defaultPlayerCharacter = new PlayerCharacterEntity(i as PlayerCharacterId);
                        for (const [, j] of pairs(PlayerCharacterColums)) {
                            // const column = (i as PlayerDataColums)
                            if (!(playerCharacter[j as PlayerCharacterColums])) {
                                (playerCharacter[j as PlayerCharacterColums] as any) =
                                    defaultPlayerCharacter[j as PlayerCharacterColums]
                            }
                        }
                        // const stuffs = this.$c.stuffService.getWeaponLib(playerCharacter.id);
                        // const currentWeaponIndex = tonumber(playerCharacter[PlayerCharacterColums.wp]) || 0;

                        // if (!stuffs.find(stuff => stuff.index === currentWeaponIndex)) {
                        //     playerCharacter[PlayerCharacterColums.wp] = 0;
                        // }
                        // const willdelete: number[] = [];
                        // /* 处理快捷栏，去掉取消的武器 */
                        // playerCharacter[PlayerCharacterColums.quickWeapon].forEach((quickIndex, allindex) => {
                        //     quickIndex = tonumber(quickIndex) || 0;
                        //     if (quickIndex > (stuffs.size() - 1)) {
                        //         willdelete.unshift(allindex);
                        //     }
                        // })
                        // willdelete.forEach(deleteIndex => {
                        //     playerCharacter[PlayerCharacterColums.quickWeapon].remove(deleteIndex);
                        // })
                        // if (playerCharacter[PlayerCharacterColums.quickWeapon].size() === 0) {
                        //     playerCharacter[PlayerCharacterColums.quickWeapon].push(0);
                        // }

                    }
                }

            }

            this.playerDataCache.set(playerStorId, playerData)
            // // if (envconfig.devArea)
            // //     this.$c.areaService.creatArea(envconfig.devArea)
            // if (this.$c.areaService.getServerType() !== ServerType.StandardServer) {
            //     if (playerData[PlayerDataColums.areaid]) {
            //         const savedLastPlaceId = playerData[PlayerDataColums.areaid];
            //         const savedPlaceConfig = placeConfig[savedLastPlaceId];
            //         if (savedLastPlaceId && savedPlaceConfig) {
            //             this.$c.areaService.creatArea(savedLastPlaceId)
            //             // const placeid = common.getPlaceID();
            //             // if (placeid !== savedLastPlaceId) {
            //             //     const player = game.GetService('Players').GetPlayerByUserId(tonumber(playerId) || 0);
            //             //     if (player) {
            //             //         if (savedPlaceConfig.private) {
            //             //             pcall(() => {
            //             //                 this.$c.teleporterService.teleportPlayerPrivate(player, savedLastPlaceId, savedPlaceConfig.placeId)
            //             //             })
            //             //         } else {
            //             //             this.$c.placeTeleporter.Teleport(tonumber(savedLastPlaceId) || 0, player)
            //             //         }
            //             //     }

            //             // }
            //         }


            //     } else {
            //         this.$c.areaService.creatArea('default')
            //         // task.delay(1, () => {
            //         //     // const placeId = game.PlaceId + ''
            //         //     this.$c.areaService.creatArea('default')
            //         // })
            //     }
            // }

            // playerData[PlayerDataColums.areaid] = '';
            // // characters.forEach(c=>{
            // //     if(c.onlyNpc){
            // //         playerData[c.id]=undefined
            // //     }
            // // })
            // const ePack = playerData[PlayerDataColums.ePack];
            // ElementConfig.forEach(ec => {
            //     if (!ePack[ec.id]) {
            //         ePack[ec.id] = 0
            //     }
            // })
            // if (playerId)
            //     this.getGiveProducts(playerId)
        }

        return playerData;
    }
}